#include "p18f26k22.h"
#include <GenericTypeDefs.h>
#include "spi.h"

//SPI2
void spi_config(void)
{
    SS2_LAT = 0b1;  //hold CS high as default
    SS2_TRIS = 0b0;
    SCK2_TRIS = 0b0;
    SDI2_TRIS = 0b1;

    SSP2CON1bits.SSPEN = 0b0;   //Turn spi off for config
    SSP2STATbits.SMP = 0b1; //Data sampled at end of data output time
    SSP2STATbits.CKE = 0b1; //txmit occurs on active to idle
    SSP2CON1bits.CKP = 0b1; //SPI clock idle high
    SSP2CON1bits.SSPM = 0b0000; //Clock = Fosc/4 - 500kHz
    SSP2CON1bits.SSPEN = 0b1;   //Turn spi on

}

UINT16 adc_read(void)
{
    UINT16 data = 0;
    //clear CS
    SS2_LAT = 0b0;
    //Dummy write
    SSP2BUF = 0x00;
    while(!SSP2STATbits.BF){}
    SSP2BUF = 0x00;
    data = (((UINT16)SSP2BUF & 0x0F) << 12);
    while(!SSP2STATbits.BF){}
    SSP2BUF = 0x00;
    data |= ((UINT16)SSP2BUF << 4);
    while(!SSP2STATbits.BF){}
    data |= (SSP2BUF >> 4);
    //clear CS
    SS2_LAT = 0b1;

    return data;
}